package com.toy.core.web;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

public abstract class BaseController {
	
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
	}
	
	/**
	 * 保存JSON到respose中
	 */
	protected void saveJSON(HttpServletResponse response, Object object) {
		response.setContentType("text/html;charset=utf-8");
		response.setHeader("Pragma","no-cache");
		response.setHeader("Cache-Control","no-store,must-revalidate");
		response.setDateHeader("Expires", 0);
		try {
			PrintWriter pw = response.getWriter();
			pw.print(object);
			pw.flush();
			pw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void writeScripts(HttpServletResponse response,String scripts){
		StringBuffer html = new StringBuffer();
		html.append("<SCRIPT>");
		html.append(scripts);
		html.append("</SCRIPT>");
		saveJSON(response, html);
	}
}
